/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controllers;

import concursos.configuracao.Configuracao;
import controllers.exceptions.NonexistentEntityException;
import controllers.exceptions.PreexistingEntityException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import concursos.configuracao.ItemConfiguracao;
import java.util.HashSet;
import java.util.Set;

/**
 *
 * @author lucena
 */
public class ConfiguracaoJpaController {

    public ConfiguracaoJpaController() {
        emf = Persistence.createEntityManagerFactory("concursosPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Configuracao configuracao) throws PreexistingEntityException, Exception {
        if (configuracao.getItens() == null) {
            configuracao.setItens(new HashSet<ItemConfiguracao>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Set<ItemConfiguracao> attachedItens = new HashSet<ItemConfiguracao>();
            for (ItemConfiguracao itensItemConfiguracaoToAttach : configuracao.getItens()) {
                itensItemConfiguracaoToAttach = em.getReference(itensItemConfiguracaoToAttach.getClass(), itensItemConfiguracaoToAttach.getId());
                attachedItens.add(itensItemConfiguracaoToAttach);
            }
            configuracao.setItens(attachedItens);
            em.persist(configuracao);
            for (ItemConfiguracao itensItemConfiguracao : configuracao.getItens()) {
                Configuracao oldConfiguracaoOfItensItemConfiguracao = itensItemConfiguracao.getConfiguracao();
                itensItemConfiguracao.setConfiguracao(configuracao);
                itensItemConfiguracao = em.merge(itensItemConfiguracao);
                if (oldConfiguracaoOfItensItemConfiguracao != null) {
                    oldConfiguracaoOfItensItemConfiguracao.getItens().remove(itensItemConfiguracao);
                    oldConfiguracaoOfItensItemConfiguracao = em.merge(oldConfiguracaoOfItensItemConfiguracao);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findConfiguracao(configuracao.getId()) != null) {
                throw new PreexistingEntityException("Configuracao " + configuracao + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Configuracao configuracao) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Configuracao persistentConfiguracao = em.find(Configuracao.class, configuracao.getId());
            Set<ItemConfiguracao> itensOld = persistentConfiguracao.getItens();
            Set<ItemConfiguracao> itensNew = configuracao.getItens();
            Set<ItemConfiguracao> attachedItensNew = new HashSet<ItemConfiguracao>();
            for (ItemConfiguracao itensNewItemConfiguracaoToAttach : itensNew) {
                itensNewItemConfiguracaoToAttach = em.getReference(itensNewItemConfiguracaoToAttach.getClass(), itensNewItemConfiguracaoToAttach.getId());
                attachedItensNew.add(itensNewItemConfiguracaoToAttach);
            }
            itensNew = attachedItensNew;
            configuracao.setItens(itensNew);
            configuracao = em.merge(configuracao);
            for (ItemConfiguracao itensOldItemConfiguracao : itensOld) {
                if (!itensNew.contains(itensOldItemConfiguracao)) {
                    itensOldItemConfiguracao.setConfiguracao(null);
                    itensOldItemConfiguracao = em.merge(itensOldItemConfiguracao);
                }
            }
            for (ItemConfiguracao itensNewItemConfiguracao : itensNew) {
                if (!itensOld.contains(itensNewItemConfiguracao)) {
                    Configuracao oldConfiguracaoOfItensNewItemConfiguracao = itensNewItemConfiguracao.getConfiguracao();
                    itensNewItemConfiguracao.setConfiguracao(configuracao);
                    itensNewItemConfiguracao = em.merge(itensNewItemConfiguracao);
                    if (oldConfiguracaoOfItensNewItemConfiguracao != null && !oldConfiguracaoOfItensNewItemConfiguracao.equals(configuracao)) {
                        oldConfiguracaoOfItensNewItemConfiguracao.getItens().remove(itensNewItemConfiguracao);
                        oldConfiguracaoOfItensNewItemConfiguracao = em.merge(oldConfiguracaoOfItensNewItemConfiguracao);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                long id = configuracao.getId();
                if (findConfiguracao(id) == null) {
                    throw new NonexistentEntityException("The configuracao with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(long id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Configuracao configuracao;
            try {
                configuracao = em.getReference(Configuracao.class, id);
                configuracao.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The configuracao with id " + id + " no longer exists.", enfe);
            }
            Set<ItemConfiguracao> itens = configuracao.getItens();
            for (ItemConfiguracao itensItemConfiguracao : itens) {
                itensItemConfiguracao.setConfiguracao(null);
                itensItemConfiguracao = em.merge(itensItemConfiguracao);
            }
            em.remove(configuracao);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Configuracao> findConfiguracaoEntities() {
        return findConfiguracaoEntities(true, -1, -1);
    }

    public List<Configuracao> findConfiguracaoEntities(int maxResults, int firstResult) {
        return findConfiguracaoEntities(false, maxResults, firstResult);
    }

    private List<Configuracao> findConfiguracaoEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("select object(o) from Configuracao as o");
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Configuracao findConfiguracao(long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Configuracao.class, id);
        } finally {
            em.close();
        }
    }

    public int getConfiguracaoCount() {
        EntityManager em = getEntityManager();
        try {
            return ((Long) em.createQuery("select count(o) from Configuracao as o").getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
